<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>WebSocket Test</title>
</head>
<body>
	<input type="text" id="wsurl" value="ws://localhost:8080/websocket/message" style="height:30px;width: 100%"/>
	<button type="button" onclick="link()" style="width: 30%;height: 50px;">连接</button>
	<button type="button" onclick="send()" style="width: 30%;height: 50px;">发送</button>
	<button type="button" onclick="nolink()" style="width: 30%;height: 50px;">断开</button>
<script>
   var socket = null;
   var connected = false;
   
	function link(){
		if (socket) {
		  nolink();
		}
		var wsurl = document.getElementById('wsurl').value;
		socket = new WebSocket(wsurl);
		// 连接成功时触发
		socket.onopen = function(event) {
		    socket.send("Hello, Server!");
		};
		 
		// 接收到消息时触发
		socket.onmessage = function(event) {
		    console.log("Received data: " + event.data);
		};
		 
		// 连接关闭时触发
		socket.onclose = function(event) {
		    console.log("Connection closed.");
		};
		
		// 当有错误发生时触发
		socket.onerror = function(error) {
			   console.error('WebSocket 出错: ' + error);
		};
		connected=true;
	}
	
	function send(){
		let now = new Date();
		console.log(formatDate(now));
		if (connected) {
			socket.send(formatDateTime(now));
		}
	}
	
	function nolink(){
		if (socket) {
		  socket.close();
		  socket = null;
		  connected = false;
		}
	}
 
	function formatDate(date) {
	  return new Intl.DateTimeFormat('zh-CN').format(date);
	}
	
	
	function formatDateTime(date) {
	  function two(num) {
		let r = '';
	    r += num < 10 ? '0' : '';
		return r+num;
	  }
	  
	 function three(num) {
		let r = '';
		if(num<10){
			r='00'+num;
		}
		else if(num>=10 && num<100){
			r='0'+num;
		}
		else{
			r=num;
		}
		return r;
	 }
	 
	  var year = date.getFullYear();
	  var month = two(date.getMonth() + 1);
	  var day = two(date.getDate());
	  var hours = two(date.getHours());
	  var minutes = two(date.getMinutes());
	  var seconds = two(date.getSeconds());
	  var milliseconds = three(date.getMilliseconds());
	 
	  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}:${milliseconds}`;
	}
</script>
</body>
</html>
